package com.analysis.behaviorlogtracing.plugin

import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes

class ASMUtil {

    public static byte[] editClass(byte[] srcClass) {
        try {
            ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS)
            ClassVisitor classVisitor = new BehaviorLogTracingClassVisitor(classWriter)
            ClassReader cr = new ClassReader(srcClass)
            cr.accept(classVisitor, ClassReader.EXPAND_FRAMES)
            return classWriter.toByteArray()
        } catch (Exception ex) {
            ex.printStackTrace()
            return srcClass
        }
    }

    public static void insertCommonLog(MethodVisitor methodVisitor,
                                       String className, String methodName) {
        methodVisitor.visitLdcInsn(className)
        methodVisitor.visitLdcInsn(methodName)
        methodVisitor.visitMethodInsn(
                Opcodes.INVOKESTATIC,
                "com/analysis/demo/ASMLogUtil",
                "onASMLogPrint",
                "(Ljava/lang/String;Ljava/lang/String;)V",
                false
        )
    }

    public static void insertClickEvent(MethodVisitor methodVisitor, String className) {
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1)
        methodVisitor.visitLdcInsn(className)
        methodVisitor.visitMethodInsn(
                Opcodes.INVOKESTATIC,
                "com/analysis/demo/ASMLogUtil",
                "onASMClickLogPrint",
                "(Landroid/view/View;Ljava/lang/String;)V",
                false
        )
    }

}